import React from 'react';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { blogPosts } from '../../data/blogPosts';
import './LatestBlogPosts.css';

const LatestBlogPosts = () => {
  // 获取最新的3篇博客文章
  const latestPosts = blogPosts.slice(0, 3);
  
  // 使用intersection observer检测元素是否可见
  const [ref, inView] = useInView({
    triggerOnce: true,
    threshold: 0.1
  });

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: {
        duration: 0.5
      }
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
  };

  return (
    <section className="latest-posts section">
      <div className="container">
        <div className="section-header">
          <h2 className="section-title">最新博客</h2>
          <p className="section-subtitle">
            分享我对技术、设计和行业趋势的见解与经验
          </p>
        </div>

        <motion.div 
          className="posts-grid"
          ref={ref}
          variants={containerVariants}
          initial="hidden"
          animate={inView ? 'visible' : 'hidden'}
        >
          {latestPosts.map((post) => (
            <motion.div key={post.id} className="post-card" variants={itemVariants}>
              <div className="post-image-container">
                <img 
                  src={post.coverImage} 
                  alt={post.title} 
                  className="post-image" 
                />
                <div className="post-category">{post.category}</div>
              </div>
              <div className="post-content">
                <div className="post-meta">
                  <span className="post-date">{formatDate(post.date)}</span>
                </div>
                <h3 className="post-title">
                  <Link to={`/blog/${post.id}`}>{post.title}</Link>
                </h3>
                <p className="post-excerpt">{post.excerpt}</p>
                <Link to={`/blog/${post.id}`} className="read-more">
                  阅读全文
                </Link>
              </div>
            </motion.div>
          ))}
        </motion.div>

        <div className="view-all-container">
          <Link to="/blog" className="btn btn-outline view-all-btn">
            查看全部文章
          </Link>
        </div>
      </div>
    </section>
  );
};

export default LatestBlogPosts;
